package ch.ethz.fcl.metrobuzz.render.techniques.colors;

public class MBColorFactory {
	public static MBColor create(int r, int g, int b) {
		float[] hsv = rgbToHSV(r / 255.0f, g / 255.0f, b / 255.0f);
		return new MBColor(hsv);
	}

	public static float[] rgbToHSV(float r, float g, float b) {
		float h, s, v;
		float mthis, max, delta;

		mthis = r < g ? r : g;
		mthis = mthis < b ? mthis : b;

		max = r > g ? r : g;
		max = max > b ? max : b;

		v = max; // v
		delta = max - mthis;
		if (max > 0.0) {
			s = (delta / max); // s
		} else {
			s = 0.0f;
			h = 0;
		}
		if (r >= max)
			h = (g - b) / delta;
		else if (g >= max)
			h = 2.0f + (b - r) / delta;
		else
			h = 4.0f + (r - g) / delta;

		h *= 60.0; // degrees

		if (h < 0.0)
			h += 360.0f;

		float[] hsv = { h, s, v };
		return hsv;
	}

	public static float[] hsvToRGB(float h, float s, float v) {
		float hh, p, q, t, ff;
		int i;

		float r, g, b;

		if (s <= 0.0) {
			if (h <= 0) {
				r = v;
				g = v;
				b = v;
			} else {
				r = 0.0f;
				g = 0.0f;
				b = 0.0f;
			}
		} else {
			hh = h;
			if (hh >= 360)
				hh = 0.0f;
			hh /= 60.0f;
			i = (int) hh;
			ff = hh - i;
			p = v * (1.0f - s);
			q = v * (1.0f - (s * ff));
			t = v * (1.0f - (s * (1.0f - ff)));

			switch (i) {
			case 0:
				r = v;
				g = t;
				b = p;
				break;
			case 1:
				r = q;
				g = v;
				b = p;
				break;
			case 2:
				r = p;
				g = v;
				b = t;
				break;

			case 3:
				r = p;
				g = q;
				b = v;
				break;
			case 4:
				r = t;
				g = p;
				b = v;
				break;
			case 5:
			default:
				r = v;
				g = p;
				b = q;
				break;
			}

		}

		float[] rgb = { r, g, b };
		return rgb;
	}
}
